package panda.client.ui.widgets;

import panda.client.engine.Observable;
import panda.client.engine.Observer;
import panda.client.enumerations.ZIndexLevel;
import panda.client.ui.observable.ObservableLastMousedCard;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;

/**
 * Manages zooming of DraggableCards on Panda.canvas. Observes LastMousedCard.java and whenever it updates, ZoomManager
 * updates the card being zoomed in on.
 * 
 * @author zane.tian@gmail.com
 */
public class ZoomManager implements Observer {
	private final PopupPanel popup;
	private boolean zooming;
	private Image img;

	public ZoomManager(ObservableLastMousedCard card) {
		popup = new PopupPanel();
		DOM.setStyleAttribute(popup.getElement(), "zIndex", String.valueOf(ZIndexLevel.ZOOMCARD.getZIndex()));
		// Image cardBack = new Image("card-back-clipped.jpg");
		// cardBack.setSize(CardScale.FULL.getWidth() + "px", CardScale.FULL.getHeight() + "px");
		img = new Image("img/card-back-clipped.jpg");
		popup.add(img);
		zooming = false;
		card.addObserver(this);
	}

	public boolean isZooming() {
		return zooming;
	}

	public void setZooming(boolean zooming) {
		this.zooming = zooming;
	}

	public void update(Observable o, Object arg) {
		ObservableLastMousedCard lastCard = (ObservableLastMousedCard) o;
		// System.out.println("[c] zoom-manager updating o: " + o);
		if(lastCard.hasCard()) { /* sometimes it can be, like when you put a card into a bin */
			DraggableCard card = ((ObservableLastMousedCard) o).getCard();

			String url = ((Image) popup.getWidget()).getUrl();

			/**
			 * quick check to make sure we're not updating the same card: url is in format
			 * http://localhost:8888/panda.PandaApp/cardsets/shm/75percent/202.jpg but card.getZoomUrl() will be
			 * /cardsets/shm/75percent/202.jpg, hence the contains() check
			 */
			if(!url.contains(card.getZoomUrl())) {
				replace(card);
				// CanvasLog.get().log("card updated in zoomManager: " + card.getZoomUrl());
			}
		}
	}

	private void replace(DraggableCard card) {
		// popup.clear();
		// popup.add(new Image(card.getZoomUrl()));
		img.setUrl(card.getZoomUrl());
		// if(zooming) {
		// NoteTip.get().logPersonalNote("Zooming into " + card.getName() + " at " + card.getZoomUrl(), true);
		// }
	}

	public void show(DraggableCard card) {
		setZooming(true);

		replace(card);
		popup.center();
	}

	public void hide() {
		popup.hide();
		setZooming(false);
	}
}